#coding=utf-8
from uliweb.orm import *

    
class MenuRole(Model):
    """
    菜单角色
    """
    name = Field(str, max_length=80, required=True)
    description = Field(str, max_length=255)
    category = Reference('rolecategory', nullable=True)
    reserve = Field(bool)
    users = ManyToMany('user', collection_name='user_menurole')
    menus = ManyToMany('menu', collection_name='menu_menurole')
    usergroups = ManyToMany('usergroup', collection_name='usergroup_menurole')
    relative_usergroup = Reference('usergroup', nullable=True)

class ResourceType(Model):
    """
    资源类型，用于表示是菜单还是操作功能
    """
    resourcetype_name = Field(str,verbose_name="资源类型 0:菜单 1:功能", max_length=10, required=True)
    resourcetype_id = Field(int,verbose_name="资源类型ID")
    
class Permission(Model):
    """
    操作权限
    """
    name = Field(str, max_length=80, required=True)
    description = Field(str, max_length=255)
    props = Field(PICKLE)
    url = Field(str, verbose_name="访问url", max_length=255)
    pid = Field(str, verbose_name="上级菜单",max_length=10)
    resourcetype = Reference('resourcetype', reference_fieldname='resourcetype_id')
    
    def get_users(self):
        for role in self.perm_roles.all():
            for u in role.users.all():
                yield u
                
    def get_users_ids(self):
        for role in self.perm_roles.all():
            for u in role.users.ids():
                yield u
    
    def __unicode__(self):
        return self.name
